/*
 * @Descripttion:
 * @version:
 * @Author: sueRimn
 * @Date: 2021-10-30 11:25:08
 * @LastEditors: sueRimn
 * @LastEditTime: 2021-12-14 23:33:29
 */
var mqtt = require('../utils/mqtt.min.js');
const crypto = require('../utils/hex_hmac_sha1.js'); //根据自己存放的路径修改
var res_data = new Array(12);
var read_data_end_flag = 0;


var client = null;

var  ICON = {

  img_hea: '${BASE_PATH}/images/001.jpg',
  img_dia: '../images/002.jpg',
  img_spa: '../images/003.jpg',
  img_clu: '../images/004.jpg',
  // 添加更多图标...
}

function get_message(array)
{


  // if (array.length % 2 != 0 || array.length < 40) {
  //   console.log("FRAM_ERR_LEN");
  //   this.read_data_end_flag = 1;
  //   return null;
  // }
  
  for (var i = 0; i < array.length / 2; i++) {
    // console.log(i + " " + array[2 * i] + " " + array[2 * i + 1] )

    if ("0".charCodeAt() <= array[2 * i] && array[2 * i] <= "9".charCodeAt())
    this.res_data[i] = (array[2 * i] - "0".charCodeAt()) * 0x10;
    else this.res_data[i] = (array[2 * i] - "a".charCodeAt() + 0xa) * 0x10;

    if (
      "0".charCodeAt() <= array[2 * i + 1] &&
      array[2 * i + 1] <= "9".charCodeAt()
    )
    this.res_data[i] += array[2 * i + 1] - "0".charCodeAt();
    else this.res_data[i] += array[2 * i + 1] - "a".charCodeAt() + 0xa;
 
    // temp_ch += "0x" + res_data[i].toString(16) + " "
  }
  // console.log(this.res_data)
  this.read_data_end_flag = 1;
}

function signHmacSha1(params, deviceSecret) {

  let keys = Object.keys(params).sort();
  // 按字典序排序
  keys = keys.sort();
  const list = [];
  keys.map((key) => {
    list.push(`${key}${params[key]}`);
  });
  const contentStr = list.join('');
  return crypto.hex_hmac_sha1(deviceSecret, contentStr);
}

//IoT平台mqtt连接参数初始化
function initMqttOptions(deviceConfig) {

  const params = {
    productKey: deviceConfig.productKey,
    deviceName: deviceConfig.deviceName,
    timestamp: Date.now(),
    clientId: Math.random().toString(36).substr(2),
  }
  //CONNECT参数
  const options = {
    keepalive: 60, //60s
    clean: true, //cleanSession不保持持久会话
    protocolVersion: 4 //MQTT v3.1.1
  }
  //1.生成clientId，username，password
  options.password = signHmacSha1(params, deviceConfig.deviceSecret);
  options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
  options.username = `${params.deviceName}&${params.productKey}`;

  return options;
}

/*
  生成基于HmacSha1的password
  参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
*/


function doConnect() {
  const deviceConfig = {
    productKey: "gcq62tJ5vZT",
    deviceName: "master",
    deviceSecret: "6590da0cc63f19f7d32130572a13d78c",
    regionId: "cn-shanghai"//根据自己的区域替换
  };
  const options = initMqttOptions(deviceConfig);
  console.log(options)
  //替换productKey为你自己的产品的（注意这里是wxs，不是wss，否则你可能会碰到ws不是构造函数的错误）
  this.client = mqtt.connect('wxs://productKey.iot-as-mqtt.cn-shanghai.aliyuncs.com', options)
  this.client.on('connect', (e) =>{
    console.log('连接服务器成功')
    //注意：订阅主题，替换productKey和deviceName(这里的主题可能会不一样，具体请查看控制台-产品详情-Topic 类列表下的可订阅主题)，并且确保改主题的权限设置为可订阅
    this.client.subscribe('/gcq62tJ5vZT/master/user/device_up',  (err) =>{
      if (!err) {
        console.log('订阅成功！');
      }
    })
  })
  //接收消息监听
  var that = this
  this.client.on('message', function (topic, message) {
    // message is Buffer
    // let msg = message.toString();
    that.get_message(message)
    // console.log('收到消息：' + msg);
    //关闭连接 client.end()
  })
}
// function doConnect() {
//   var that = this
//     wx.request({
//        //设备ID
//       //api-key
//       url: 'http://api.heclouds.com/devices/765806075/datapoints?', //xxxxxxxxxx这里填写你的设备id
//       header:{
//         "api-key":"mELiXttCI7XL2yjzGIEqA1kFCm4=/ykQ="  //这里写你的api-key
//       },
//       data:{
//         limit:1
//       },
//       method :"GET",
//        //获取成功
//       success:function(res){
//       //  that.setData({
//       //  shidu:res.data.data.datastreams[0].datapoints[0].value, //这里的shidu要跟wxml{{shidu}} 名字相同
//       //  wendu:res.data.data.datastreams[1].datapoints[0].value,
//       //  })    
//       }
//     })
// }
function hextostr(array) {
  var val = "";

  for (var i = 0; i < array.length; i++) {
    if (array[i] < 0x0f) {
      val += "0";
      val += array[i].toString(16);
    } else {
      val += array[i].toString(16);
    }
  }
  return val;
}
module.exports = {
  // connectMqtt, connectMqtt
  client:client,
  doConnect:doConnect,
  hextostr:hextostr,
  get_message:get_message,
  res_data:res_data,
  read_data_end_flag:read_data_end_flag,
  ICON:ICON,
}
